package cn.itcast.service.impl;

import cn.itcast.dao.MemberDao;
import cn.itcast.dao.OrderDao;
import cn.itcast.dao.SetmealDao;
import cn.itcast.entity.EchartsResult;
import cn.itcast.entity.Result;
import cn.itcast.entity.SetmealResult;
import cn.itcast.pojo.Vo.ReportSetmeal;
import cn.itcast.pojo.data4Month;
import cn.itcast.pojo.Order;
import cn.itcast.pojo.Setmeal;
import cn.itcast.pojo.Vo.MonthAndNumber;
import cn.itcast.service.ReportService;
import cn.itcast.utils.DateUtils;
import cn.itcast.vo.IncomeStatisticalVo;
import cn.itcast.vo.OrderStatisticalVo;
import cn.itcast.vo.ReportDataVo;
import cn.itcast.vo.SetmealVo;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private OrderDao orderDao;

    @Override
    public Result setmeals() {
        //创建保存套餐名称集合
        List<String> setmealNames = new ArrayList<>();
        //创建保存套餐数量集合
        List<Integer> setmealCount = new ArrayList<>();
        List<ReportSetmeal> list  =  orderDao.setmeals();
        System.out.println(list);
        for (ReportSetmeal setmeal : list) {
            setmealNames.add(setmeal.getName());
            setmealCount.add(setmeal.getNumbers());
        }

        //封装成一个集合 集合里面的元素是value和name的键值对
        List<Map> lists = new ArrayList<>();
        for (int i = 0; i < setmealCount.size(); i++) {
            Map map = new HashMap();
            map.put("value",setmealCount.get(i));
            map.put("name",setmealNames.get(i));
            lists.add(map);
        }

        return (setmealNames.size()>0 && setmealCount.size()>0)?
                new Result(true,"套餐饼图生成成功",lists):
                new Result(false,"套餐饼图生成失败",null);
    }

    @Autowired
    private SetmealDao setmealDao;

    /**
     * 查询本月本周运营数据统计
     *
     * @return
     */
    @Override
    public Result business() throws Exception {
        ReportDataVo vo = new ReportDataVo();
        Date todayDate = DateUtils.getToday();
        String today = new SimpleDateFormat("yyyy-MM-dd").format(todayDate);
        //设置当前日期
        vo.setReportDate(today);

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -7);
        Date thisWeekDate = calendar.getTime();
        String thisWeekDay = DateUtils.parseDate2String(thisWeekDate, "yyyy-MM-dd");

        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -1);
        Date thisMonthDate = c.getTime();
        String thisMonthDay = DateUtils.parseDate2String(thisMonthDate, "yyyy-MM-dd");

        //查找今日新增会员数
        Integer memberTodayCount = memberDao.findNewMembers(today);
        vo.setTodayNewMember(memberTodayCount);

        //查找总会员数
        Integer totalMember = memberDao.findTotalMember();
        vo.setTotalMember(totalMember);

        //查找本周新增会员数
        Integer memberWeekCount = memberDao.findNewMembersByTime(today, thisWeekDay);
        vo.setThisWeekNewMember(memberWeekCount);

        //查找本月新增会员数
        Integer memberMonthCount = memberDao.findNewMembersByTime(today, thisMonthDay);
        vo.setThisMonthNewMember(memberMonthCount);

        //查找今日预约数
        Integer todayOrderCount = orderDao.findNewOrder(today);
        vo.setTodayOrderNumber(todayOrderCount);

        //查找今日到诊数
        Integer todayVisitsNumber = orderDao.findTodayVisits(today);
        vo.setTodayVisitsNumber(todayVisitsNumber);

        //查找本周预约数
        Integer weekOrderCount = orderDao.findOrderByTime(today, thisWeekDay);
        vo.setThisWeekOrderNumber(weekOrderCount);

        //查找本周到诊数
        Integer weekVisitsCount = orderDao.findWeekVisitsByTime(today, thisWeekDay);
        vo.setThisWeekVisitsNumber(weekVisitsCount);

        //查找本月预约数
        Integer monthOrderCount = orderDao.findOrderByTime(today, thisMonthDay);
        vo.setThisMonthOrderNumber(monthOrderCount);

        //查找本月到诊数
        Integer monthVisitsCount = orderDao.findWeekVisitsByTime(today, thisMonthDay);
        vo.setThisMonthVisitsNumber(monthVisitsCount);

        //查找
        List<Order> orders = orderDao.findAll();//查询所有订单
        List<SetmealVo> setmealVos = new ArrayList<>();
        Integer totalCount = orders.size();//查询订单条数

        Map<Integer, Order> map = new HashMap<>();
        orders.forEach(order -> {
            Integer setmealId = order.getSetmealId();
            if (!map.containsKey(setmealId)) {
                map.put(setmealId, order);
            }
        });
//        Map<Integer, Order> map = orders.stream().collect(Collectors.toMap(Order::getSetmealId, order -> order));
        List<Setmeal> setmeals = setmealDao.findAll();
        setmeals.forEach(setmeal -> {
            Order order = map.get(setmeal.getId());
            SetmealVo setmealVo = new SetmealVo();
            setmealVo.setName(setmeal.getName());
            //通过setmeal中的id查询订单表中该套餐的条数
            Integer setmeal_count = orderDao.findSetmealCount(setmeal.getId());
            setmealVo.setSetmeal_count(setmeal_count);
            System.out.println("setmeal_count = " + setmeal_count);
            System.out.println("totalCount = " + totalCount);
            //计算所占比例
            double proportion = setmeal_count / 1.0 / totalCount;
//            Long round = Math.round(proportion * 100);
//            proportion = Double.valueOf(round.toString()) / 100.0;
            proportion = Double.parseDouble(new DecimalFormat("0.00").format(proportion));

            setmealVo.setProportion(proportion);
            setmealVos.add(setmealVo);

        });

        vo.setHotSetmeal(setmealVos);
        return new Result(true, "查询成功！", vo);
    }

    @Override
    public void export() {

    }


    /**
     * 收入统计
     *
     * @return
     */
//    @Override
//    public IncomeStatisticalVo incomeStatistical() {
//
//        //12月前的所有月份
//        List<String> months = DateUtils.getLast12Months(new Date());
//
//        List<data4Month> list = orderDao.findIncomeStatistics();
//        //将这个转化为月份和收入对应的map
//        List<Integer> incomeList = new ArrayList<>();
//        List<String> dateList = new ArrayList<>();
//        IncomeStatisticalVo vo = new IncomeStatisticalVo();
//
//        Map<String, Integer> map = list.stream()
//                .collect(Collectors.toMap(data4Month::getDate, data4Month::getNum));
//        for (String month : months) {
//            if (!map.containsKey(month)) {
//                dateList.add(month);
//                incomeList.add(0);
//            } else {
//                dateList.add(month);
//                incomeList.add(map.get(month));
//            }
//        }
//        vo.setIncomeList(incomeList);
//        vo.setDateList(dateList);
//        return vo;
//    }

    /**
     * 订单及支付统计
     *
     * @return
     */
//    @Override
//    public OrderStatisticalVo orderStatistical() {
//        //12月前的所有月份
//        List<String> months = DateUtils.getLast12Months(new Date());
//
//        //查询预约数量
//        List<data4Month> orderlist = orderDao.findOrderStatistics();
//        System.out.println("orderlist = " + orderlist);
//        //查询支付数量
//        List<data4Month> paylist = orderDao.findPayStatistics();
//        System.out.println("paylist = " + paylist);
//
//
//        //修改
//        return null;
//    }


    /**
     * 收入统计
     *
     * @return
     */
    @Override
    public IncomeStatisticalVo incomeStatistical() {

        //12月前的所有月份
        List<String> months = DateUtils.getLast12Months(new Date());

        List<data4Month> list = orderDao.findIncomeStatistics();
        //将这个转化为月份和收入对应的map
        List<Integer> incomeList = new ArrayList<>();
        List<String> dateList = new ArrayList<>();
        IncomeStatisticalVo vo = new IncomeStatisticalVo();

        Map<String, Integer> map = list.stream()
                .collect(Collectors.toMap(data4Month::getDate, data4Month::getNum));
        for (String month : months) {
            if (!map.containsKey(month)) {
                dateList.add(month);
                incomeList.add(0);
            } else {
                dateList.add(month);
                incomeList.add(map.get(month));
            }
        }
        vo.setIncomeList(incomeList);
        vo.setDateList(dateList);
        return vo;
    }

    /**
     * 订单及支付统计
     *
     * @return
     */
    @Override
    public OrderStatisticalVo orderStatistical() {
        //12月前的所有月份
        List<String> months = DateUtils.getLast12Months(new Date());

        //查询预约数量
        List<data4Month> orderlist = orderDao.findOrderStatistics();
        System.out.println("orderlist = " + orderlist);
        //查询支付数量
        List<data4Month> paylist = orderDao.findPayStatistics();
        System.out.println("paylist = " + paylist);

        //将这个转化为月份和收入对应的map
        List<Integer> orderNumList = new ArrayList<>();
        List<Integer> payNumList = new ArrayList<>();
        List<String> dateList = new ArrayList<>();
        OrderStatisticalVo vo = new OrderStatisticalVo();

        Map<String, Integer> orderMap = orderlist.stream()
                .collect(Collectors.toMap(data4Month::getDate, data4Month::getNum));
        for (String month : months) {
            if (!orderMap.containsKey(month)) {
                dateList.add(month);
                orderNumList.add(0);
            } else {
                dateList.add(month);
                orderNumList.add(orderMap.get(month));
            }
        }
        Map<String, Integer> payMap = paylist.stream()
                .collect(Collectors.toMap(data4Month::getDate, data4Month::getNum));
        for (String month : months) {
            if (!payMap.containsKey(month)) {
                payNumList.add(0);
            } else {
                payNumList.add(payMap.get(month));
            }
        }
        vo.setOrderNumList(orderNumList);
        vo.setPayNumList(payNumList);
        vo.setDateList(dateList);
        return vo;

    }

//    @Override
//    public Result setmeals() {
//        return null;
//    }

    //查询近十二个月和对应月数的回来数量
    @Override
    public Result queryMemberAndMothods() {
        //查询数据库的月数和数量
      List<MonthAndNumber> list =   orderDao.queryMemberAndMothods();

        for (MonthAndNumber monthAndNumber : list) {
            System.out.println(monthAndNumber);
        }

      //获取当前时间年和月份
        String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        System.out.println(time);

        //创建两个集合 保存近十二个月的字符串  保存每一个月份的会员数量 不存在月数就赋值为0
        List<String> months = new ArrayList<>();
        List<Integer> members = new ArrayList<>();
        //将年和月份切割
        String[] times = time.split("-");
        Integer year = Integer.parseInt(times[0]); //年份
        Integer month = Integer.parseInt(times[1]); //月数
        String str=null;
        //遍历十二次表示近十二个月的数据
        first:for (int i = 0; i < 12; i++) {

            //转换为整数后小于10月的月份前面的0会丢失 判断加上
           if (month>=10){
              str = year.toString()+"-"+month.toString();
           }else{
                str = year.toString()+"-0"+month.toString();
           }

            //添加月数
            months.add(str);

            //添加月数的当前会员数量
            for (MonthAndNumber monthAndNumber : list) {
                String str2 = monthAndNumber.getTime();

                if (str.equals(str2)){
                    //如果纯在当前月数
                    members.add(monthAndNumber.getNumber());
                    //月数减-
                    month--;
                    if (month==0){
                        year--;
                        month=12;
                    }
                    continue first;
                }
            }
            members.add(0);
            //月数减-
            month--;
            if (month==0){
                year--;
                month=12;
            }
        }
        Collections.reverse(months);
        int monthss = months.size();
        Collections.reverse(members);
        int member = members.size();
        System.out.println(monthss+"======month");
        System.out.println(months);
        System.out.println(member+"=========member");
        System.out.println(members);

        return (months.size()>0 || members.size()>0)?
                new Result(true,"折线图表展示成功",new EchartsResult(months,members)):
                new Result(false,"折线图表展示失败",null);
    }
}